# -*- coding: utf-8 -*-
import json

from pyquery import PyQuery
from datetime import datetime
from zc_core.model.items import Catalog, Brand, Supplier, Sku, ItemData
from zc_core.pipelines.helper.supplier_helper import SupplierHelper
from zc_core.util.common import parse_number
from zc_core.util.encrypt_util import md5
from zc_core.util.sku_id_parser import convert_id2code
from ccb.matcher import *


# 解析catalog列表
def parse_catalog(response):
    rows = json.loads(response.text)

    cats = list()
    for row1 in rows:
        # 一级分类
        cat1 = _build_catalog(row1, 1)
        cats.append(cat1)

        # 二级分类
        row2_list = row1.get('childs', [])
        for row2 in row2_list:
            cat2 = _build_catalog(row2, 2)
            cats.append(cat2)

            # 三级分类
            row3_list = row2.get('childs', [])
            for row3 in row3_list:
                cat3 = _build_catalog(row3, 3)
                cats.append(cat3)

    return cats


def _build_catalog(row, level):
    cat = Catalog()
    cat_id = str(row.get('innercode'))
    cat_name = row.get('category_name')
    cat_code = row.get('primaryKey')
    parent_id = str(row.get('parent_category_id'))
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['catalogCode'] = cat_code
    if parent_id == 0:
        cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 解析sku列表页数
def parse_total_page(response):
    js = json.loads(response.text) or {}

    return js.get('result', {}).get('pageTotal', 0)


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    js = json.loads(response.text)

    sku_list = list()
    datas = js.get('result').get('data')
    for data in datas:
        sku = Sku()
        sku['batchNo'] = meta.get('batchNo')
        sku['skuId'] = str(data.get('skuid'))
        sku['skuCode'] = str(data.get('id'))
        sku['supplierSkuId'] = str(data.get('skucode'))
        sku['salePrice'] = data.get('tax_price')
        sku['soldCount'] = data.get('sales_volume')
        sku_list.append(sku)

    return sku_list


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    js = json.loads(response.text)
    data = js.get('data')

    data_list = list()
    item = ItemData()
    item['batchNo'] = meta.get('batchNo')
    item['skuId'] = sku_id
    item['spuId'] = sku_id
    item['skuCode'] = data.get('sup_category_id', '')
    item['salePrice'] = data.get('tax_price')
    item['originPrice'] = parse_number(data.get('cPrice', '-1'))
    item['soldCount'] = data.get('onsaled', 0)
    item['skuName'] = data.get('title')
    brand = data.get('brand', {})
    if brand:
        item['brandName'] = brand.get('brand_name')
        item['brandId'] = str(brand.get('brand_id'))
    item['unit'] = data.get('unit', '')
    item['skuImg'] = data.get('main_picture', {}).get('uri_large', '')
    cats = data.get('classPathMap', {})
    if cats:
        cat3 = cats.get('path1', {})
        if cat3:
            item['catalog3Id'] = cat3.get('code')
            item['catalog3Name'] = cat3.get('name')
        cat2 = cats.get('path2', {})
        if cat2:
            item['catalog2Id'] = cat2.get('code')
            item['catalog2Name'] = cat2.get('name')
        cat1 = cats.get('path3', {})
        if cat1:
            item['catalog1Id'] = cat1.get('code')
            item['catalog1Name'] = cat1.get('name')
    item['supplierId'] = str(data.get('channelId'))
    item['supplierName'] = data.get('channelName')
    item['supplierSkuId'] = str(data.get('ext_skuid'))
    data_list.append(item)

    rows = data.get('compareProducts', [])
    if rows and rows[0]:
        cp_data = rows[0]
        data1 = cp_data.get('data1', {})
        if data1:
            rs1 = _build_compare_item(data1, item)
            data_list.append(rs1)
        data2 = cp_data.get('data2', {})
        if data2:
            rs2 = _build_compare_item(data2, item)
            data_list.append(rs2)
        data3 = cp_data.get('data3', {})
        if data3:
            rs3 = _build_compare_item(data3, item)
            data_list.append(rs3)

    return data_list


def _build_compare_item(data, item):
    rs = ItemData()
    rs['batchNo'] = item.get('batchNo')
    rs['skuId'] = str(data.get('id', ''))
    rs['spuId'] = item.get('spuId', '')
    rs['skuCode'] = data.get('cpu_product_id', '')
    rs['salePrice'] = parse_number(data.get('tax_price'))
    rs['originPrice'] = item['salePrice']
    rs['skuName'] = data.get('name')
    rs['brandName'] = item.get('brandName')
    rs['brandId'] = str(item.get('brandId'))
    rs['unit'] = item.get('unit', '')
    rs['skuImg'] = item.get('img_url', {}).get('uri_large', '')
    rs['catalog3Id'] = item.get('catalog3Id')
    rs['catalog3Name'] = item.get('catalog3Name')
    rs['catalog2Id'] = item.get('catalog2Id')
    rs['catalog2Name'] = item.get('catalog2Name')
    rs['catalog1Id'] = item.get('catalog1Id')
    rs['catalog1Name'] = item.get('catalog1Name')
    # rs['supplierId'] = str(data.get('channelId'))
    rs['supplierName'] = data.get('source_name')
    rs['supplierSkuId'] = data.get('sku_code')

    return rs


# 解析ItemData
def parse_item_datax(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    result = ItemData()

    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    nav = jpy('div.breadmain a')
    sale_price = match_sale_price(response.text)
    origin_price = jpy('del#website_price_tag').text()
    total_sales = jpy('div.cumulativeamount').text()
    # 品 目 编 号
    gov_catalog_id = jpy('div.attribute div.dt:contains("品") + div.gs').eq(0).text()
    # 商 品 编 号
    supplier_sku_id = jpy('div.attribute div.dt:contains("商") + div.gs').eq(0).text()
    # 供  应  商
    supplier = jpy('div.attribute div.dt:contains("供") + div.gs').eq(0)
    brand = jpy('table.Ptable td:contains("品牌") + td').text()
    model_attrs = jpy('table.Ptable td:contains("型号")')
    images = jpy('div.spec-scroll div.items li img')

    # -------------------------------------------------
    # 批次编号
    result['batchNo'] = batch_no
    # 平台商品ID（用于业务系统）
    result['skuId'] = sku_id
    # 平台商品名称（标题）
    result['skuName'] = jpy('div.goodsdetail_left h1').eq(0).text().strip()
    # 平台商品主图（主图地址）
    if images:
        result['skuImg'] = images.eq(0).attr('src').strip()
    # 一级分类编号
    result['catalog1Id'] = ''
    # 一级分类名称
    result['catalog1Name'] = ''
    # 二级分类编号
    result['catalog2Id'] = ''
    # 二级分类名称
    result['catalog2Name'] = ''
    # 三级分类编号
    # 735 清洁用品  710 清洁用品
    catalog3_id = match_cat_id(nav.eq(1).attr('href'))
    # TODO 兼容错误数据
    if catalog3_id == '735':
        catalog3_id = '710'
    if catalog3_id == '804':
        catalog3_id = '817'
    result['catalog3Id'] = catalog3_id
    # 三级分类名称
    result['catalog3Name'] = nav.eq(1).text().strip()
    # 政府采购品目编码
    if gov_catalog_id and gov_catalog_id != '暂无':
        result['govCatId'] = gov_catalog_id.strip()
    # 实际销售价格
    result['salePrice'] = parse_number(sale_price)
    # 商品原价（商城原价、市场价格）
    result['originPrice'] = parse_number(origin_price)
    # 累积采购金额
    result['soldAmount'] = parse_number(total_sales)
    # 品牌
    if brand and brand.strip():
        result['brandName'] = brand.strip()
        result['brandId'] = md5(brand.strip())
    # 供应商
    sp_name = supplier('font.textm').text()
    if sp_name and sp_name.strip():
        result['supplierName'] = sp_name.strip()
        result['supplierId'] = md5(sp_name.strip())
    # 供应商商品编码
    sp_sku_id = supplier_sku_id.strip()
    result['supplierSkuId'] = sp_sku_id
    plat_code = None
    if sp_name == '得力':
        plat_code = 'deli'
    result['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
    # 供应商商品链接
    if supplier:
        result['supplierSkuLink'] = supplier('a').attr('href').strip()
    # 品牌型号
    if model_attrs and len(model_attrs):
        for model_attr in model_attrs.items():
            if model_attr.text().strip() == '型号':
                model = model_attr.next('td').text().strip()
                if model:
                    result['brandModel'] = model[0:190]
    result['genTime'] = datetime.utcnow()
    # -------------------------------------------------

    return result
